package com.lgx.mall.core.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.common.exception.DataException;
import com.lgx.common.util.ScoreCardUtils;
import com.lgx.common.web.Constants;
import com.lgx.common.web.Pagination;
import com.lgx.common.web.json.Json2Utils;
import com.lgx.common.web.util.DateUtils;
import com.lgx.common.web.util.EscapeUtils;
import com.lgx.mall.core.entity.ScoreCard;
import com.lgx.mall.core.service.IScoreCardService;
import com.lgx.right.entity.User;
import com.lgx.right.util.PasswordUtils;

@Controller
@RequestMapping("/scoreCard")  
public class ScoreCardController {
	
	@Autowired
	private IScoreCardService scoreCardService;

	
	public IScoreCardService getScoreCardService() {
		return scoreCardService;
	}

	public void setScoreCardService(IScoreCardService scoreCardService) {
		this.scoreCardService = scoreCardService;
	}

	@RequestMapping("/scoreCardMgr.do")
	public String scoreCardMgr(HttpServletRequest request,HttpServletResponse response){
		return "/mall/core/scoreCard/scoreCardMgr";
	}
	
	
	@RequestMapping("/list.do")
	public void list(HttpServletRequest request,HttpServletResponse response){
		//接受参数
		String card = request.getParameter("card");
		String score = request.getParameter("score");
		String scoreEnd = request.getParameter("scoreEnd");   //按条件查询
		String effectiveTimeStart = request.getParameter("effectiveTimeStart");
		String effectiveTimeEnd = request.getParameter("effectiveTimeEnd");
		
		String pageNum = request.getParameter("page");
		String pageSize= request.getParameter("rows");
		
		if(StringUtils.isEmpty(pageSize))pageSize = Constants.PAGE_SIZE;
		if(StringUtils.isEmpty(pageNum))pageNum = Constants.FIRST_PAGE_NUM;
		
		User user = (User) request.getSession().getAttribute(Constants.LOGIN_USER);   //自动抓取当前登录用户的信息
		if(user != null){
			Pagination page;
			page = this.scoreCardService.findScoreCardPagination(card, score, scoreEnd, effectiveTimeStart, effectiveTimeEnd, Integer.parseInt(pageSize), Integer.parseInt(pageNum));
			Json2Utils.parseJSON(page, response);
		}
	}
	
	
	//跳转修改
	@RequestMapping("/init.do")
	public String init(HttpServletRequest request,HttpServletResponse response){
		//传入必要的操作类型和操作id
		request.setAttribute("scoreId", request.getParameter("scoreId"));
		request.setAttribute("type", request.getParameter("type"));
		return "/mall/core/scoreCard/scoreCard-init";
	}
	
	/**
	 * 添加积分卡
	 * 须按照一定规则生成
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping("/save.do")
	@ResponseBody
	public String save(HttpServletRequest request,HttpServletResponse response){
		
		String number = request.getParameter("number");                        //接受数量参数，该参数用于告知系统需要生成积分卡号的数量
		if(!StringUtils.isEmpty(number))number = EscapeUtils.unescape(number);
		
		String cardOne = request.getParameter("cardOne");                          //接受自定义规则1--CS
		if(!StringUtils.isEmpty(cardOne))cardOne = EscapeUtils.unescape(cardOne);
		
		String cardTwo = request.getParameter("cardTwo");   					   //接受自定义规则2--year
		if(!StringUtils.isEmpty(cardTwo))cardTwo = EscapeUtils.unescape(cardTwo);
		
		String cardThree = request.getParameter("cardThree");                          //接受卡号初始数值,其余卡号在此基础上累加--cardnumber
		if(!StringUtils.isEmpty(cardThree))cardThree = EscapeUtils.unescape(cardThree);
		
		String score = request.getParameter("score");
		if(!StringUtils.isEmpty(score))score = EscapeUtils.unescape(score);    //设定的卡积分
		
		String effectiveTimeStart = request.getParameter("effectiveTimeStart");
		if(!StringUtils.isEmpty(effectiveTimeStart))effectiveTimeStart = EscapeUtils.unescape(effectiveTimeStart);    //设定有效时间起始时间
		
		String effectiveTimeEnd = request.getParameter("effectiveTimeEnd");
		if(!StringUtils.isEmpty(effectiveTimeEnd))effectiveTimeEnd = EscapeUtils.unescape(effectiveTimeEnd);          //设定失效时间
		
		
		ScoreCardUtils scuts = new ScoreCardUtils();
		PasswordUtils pwd = new PasswordUtils();
		List<ScoreCard> ls = scoreCardService.findsScoreCardbyCard(cardOne.toUpperCase());   		//检索同前缀考好的存在和返回最大值
		String cardString  = "";   													//流水基数
		if(ls.size() > 0 ){//集合不为空，表示里面有这个前缀的卡号，那么，整个卡号将以这个卡号为基数执行流水操作
			cardString  = ls.get(0).getCard();   								    //改写流水基数,把查到的卡号付赋给基数
		}else{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append(cardOne);
			stringBuilder.append(cardTwo);
			stringBuilder.append(cardThree);
			
			cardString = stringBuilder.toString();                                  //将原始信息赋值给基数
		}
		
		ArrayList<String> list =  scuts.createScoreCard(cardString,1,Integer.parseInt(number));
		//根据返回的卡号循环调用添加方法
		for(int i =0;i<list.size();i++){
			
			
			ScoreCard sc = new ScoreCard();   //创建实体对象，每循环一次清空重新创建
			//存入卡号:注，在存入卡号之前，应该先去数据库中检索最新的卡号和是否有同类的卡号，有的话修改基数
			sc.setCard(list.get(i));          
			sc.setPassword(pwd.passwordRandom());         //存入密码
			sc.setScore(Double.parseDouble(score));       //存入积分
			sc.setCreateTime(new Date());     //存入创建时间
			sc.setEffectiveTimeStart(DateUtils.charToDate(effectiveTimeStart, DateUtils.DATE_FORMAT_D));  //有效起始时间
			sc.setEffectiveTimeEnd(DateUtils.charToDate(effectiveTimeEnd, DateUtils.DATE_FORMAT_D));      //有效期结束时间
			sc.setIsDelete("0");         //初始状态可用
			sc.setLocked(false);         //未锁    
			
			//调用后台
			try {
				scoreCardService.createScoreCard(sc);
			} catch (DataException e) {
				return "0";
			}
		
		}
		return "1";
	}
	
	
	@RequestMapping("/delete.do")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response){
		String ids = request.getParameter("ids");
		for(String id : ids.split(",")){
			try {
				ScoreCard sc = this.scoreCardService.findScoreCardById(Long.parseLong(id));    //查找是否存在这条信息
				if(sc!=null){
					this.scoreCardService.deleteScoreCard(sc);
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
				return "0";
			} catch (DataException e) {
				e.printStackTrace();
				return "0";
			}
		}
		return "1";
	}
	
	
	/**
	 * 检查积分卡是否可用
	 */
	/*@RequestMapping("/scoreCardChecked.do")
	public String scoreCardChecked(HttpServletRequest request,HttpServletResponse response){
		String id = request.getParameter("id");
		try {
			ScoreCard scoreCard = this.scoreCardService.findScoreCardById(Long.parseLong(id));
			request.setAttribute("scoreCard", scoreCard);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return "";
	}*/
	

}
